/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

<template>
  <div class="list">
    <div :class="[
      'music_list',
      deviceType === 'mobile' ? 'mobile_music_list' : 'pc_music_list',
    ]" v-interaction="{
      handlers: {
        onScroll: scrollMusicList,
        onSwipe: swipeMusicList,
      },
      configs: {
        enableScroll: !isShowMenu,
        enableSwipe: true,
        speed: 70
      },
    }">
      <div class="music_item" v-interaction="{
        handlers: {
          onClick: clickGoPlay,
          onDoubleClick: doubleClickGoPlay,
        },
        configs: {
          enableClick: true,
          enableDoubleClick: true,
        },
      }" v-for="item in musicList" :data-id="item.id" :key="item.id">
        <div class="music_info">
          <div class="music_name">
            <span v-interaction="{
              handlers: {
                onHover: handleHover,
              },
              configs: {
                enableHover: true,
              },
            }">{{ item.name }}</span>
            <img v-show="item.isCollect" src="../../assets/images/heart_icon.svg" />
          </div>
          <div class="music_detail">
            <span>VIP</span>
            <span>空间音频</span>
            <span>{{ item.musicName }}</span>
          </div>
        </div>
        <div class="music_icon">
          <span>
            <img src="../../assets/images/addAndsubtract.svg" />
          </span>
          <span v-interaction="{
            handlers: {
              onContextMenu: handleContextMenu,
            },
            configs: {
              enableContextMenu: true,
            },
          }">
            <img draggable="false" src="../../assets/images/detailBtn.svg" />
          </span>
        </div>
      </div>
    </div>
    <div class="contextMenuBg" @click="contextMenuBgClick" v-show="isShowMenu">
      <div ref="refMenu" class="contextMenu" v-show="isShowMenu">
        <div @click="handleCollect">
          <img v-if="musicCollect" src="../../assets/images/del_heart.svg" />
          <img v-if="!musicCollect" src="../../assets/images/add_heart.svg" />
          <span>{{ musicCollect ? "移除收藏" : "收藏到歌单" }}</span>
        </div>
        <div @click="deleteMusic">
          <img src="../../assets/images/delete.svg" />
          <span>删除</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { PointerState } from '@hadss/web_uni_input';

export default Vue.extend({
  props: {
    deviceType: {
      type: String,
      default: 'mobile',
    },
    listNum: {
      type: Number,
      default: 0,
    },
    updateMusic: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      musicList: [],
      oneMusic: {},
      musicId: null,
      clickTime: null,
      isShowMenu: false,
      musicCollect: null,
      childElement: null,
      deviceTypeLocal: this.deviceType,
      isMaxFontSize: false,
      DOUBLE_TAP_THRESHOLD: 300, // 双击超时时间间隔
    };
  },
  watch: {
    updateMusic: {
      handler(newVal) {
        if (newVal && newVal.getOneMusic) {
          newVal.getOneMusic(this.musicList[newVal.musicId - 1]);
        }
      },
      deep: true,
    },
    deviceType: {
      handler(newVal) {
        this.deviceTypeLocal = newVal;
      },
    },
  },
  methods: {
    clickGoPlay(e) {
      this.childElement = e.target;
      this.musicId = parseInt(this.childElement.closest('.music_item').dataset.id);
      this.clickTime = setTimeout(() => {
        if (!this.isShowMenu) {
          this.$router.push({
            path: '/musicListDetail',
            query: {
              isPlay: 0,
              musicId: this.musicId,
            },
          });
        }
      }, this.DOUBLE_TAP_THRESHOLD);
    },
    handleContextMenu(e) {
      this.childElement = e.target;
      this.musicId = this.childElement.closest('.music_item').dataset.id;
      const musicItem = this.musicList.find(
        (item) => item.id === Number(this.musicId)
      );
      this.musicCollect = musicItem.isCollect;
      this.isShowMenu = true;
      this.$nextTick(() => {
        this.contextMenuLocation(e);
      });
    },
    doubleClickGoPlay(e) {
      this.childElement = e.target;
      this.musicId = this.childElement.closest('.music_item').dataset.id;
      clearTimeout(this.clickTime);
      this.$router.push({
        path: '/musicListDetail',
        query: {
          isPlay: 1,
          musicId: this.musicId,
        },
      });
    },
    scrollMusicList(e) {
      const childElement = e.target;
      const parentHtml = childElement.closest('.music_list');
      const delta = e.offsetY;
      if (e.source !== "mouse") {
        const scrollStep = Math.abs(delta);
        parentHtml.scrollTo({
          top: parentHtml.scrollTop + (delta >= 0 ? -scrollStep : scrollStep),
        });
      } else {
        const scrollStep = 100;
        parentHtml.scrollTo({
          top: parentHtml.scrollTop + (delta >= 0 ? scrollStep : -scrollStep),
          behavior: 'smooth',
        });
      }
    },
    swipeMusicList(e) {
      if (window.innerWidth < 1300) {
        const childElement = e.target;
        const parentHtml = childElement.closest(".music_list");
        const height = parentHtml.getBoundingClientRect().height;
        parentHtml.scrollTo({
          top: parentHtml.scrollTop + (e.velocityY >= 0 ? -height + 60 : height - 60),
          behavior: "smooth",
        });
      }
    },
    contextMenuLocation(e) {
      const screenHeight = window.innerHeight;
      const menuWidth = this.$refs.refMenu.offsetWidth;
      const menuHeight = this.$refs.refMenu.offsetHeight;
      let left = e.clientX;
      let top = e.clientY;
      left = left - menuWidth;
      if (top + menuHeight > screenHeight) {
        top = screenHeight - menuHeight;
      }
      this.$refs.refMenu.style.left = `${left}px`;
      this.$refs.refMenu.style.top = `${top}px`;
    },
    handleCollect() {
      if (this.musicId) {
        const musicIndex = this.musicList.findIndex(
          (item) => item.id === Number(this.musicId)
        );
        if (musicIndex >= 0) {
          this.musicList[musicIndex].isCollect = !this.musicCollect;
          this.$store.commit('musicListCollect', {
            index: musicIndex,
            collect: !this.musicCollect,
          });
        }
        sessionStorage.setItem('musicList', JSON.stringify(this.musicList));
        this.isShowMenu = false;
      }
    },
    deleteMusic() {
      if (this.musicId) {
        const musicIndex = this.musicList.findIndex(
          (item) => item.id === Number(this.musicId)
        );
        if (musicIndex >= 0) {
          this.musicList.splice(musicIndex, 1);
          this.$store.commit('deleteMusiclist', this.musicList[musicIndex].id);
        }
        sessionStorage.setItem('musicList', JSON.stringify(this.musicList));
        this.isShowMenu = false;
      }
    },
    handleHover(state: PointerState) {
      if (this.isMaxFontSize) {
        state.target.style.fontSize = "16px";
        this.isMaxFontSize = false;
      } else {
        state.target.style.fontSize = "26px";
        this.isMaxFontSize = true;
      }
    },
    contextMenuBgClick() {
      this.isShowMenu = false;
    },
    handleTouchMove(e: TouchEvent) {
      const el = document.querySelector('.musicList') as HTMLElement;
      const scrollTop = el.scrollTop;
      const scrollHeight = el.scrollHeight;
      const offsetHeight = el.offsetHeight;
      const isAtTop = scrollTop === 0;
      const isAtBottom = scrollTop + offsetHeight >= scrollHeight;

      // 检查触摸点的垂直位移
      const verticalDelta = Math.abs(e.touches[0].clientY - (e.touches[0].clientY - e.touches[0].clientY));
      const horizontalDelta = Math.abs(e.touches[0].clientX - (e.touches[0].clientX - e.touches[0].clientX));

      // 如果主要是垂直滑动且在顶部或底部，禁止默认行为
      if ((isAtTop && e.touches[0].clientY > 0) || (isAtBottom && e.touches[0].clientY < 0)) {
        if (verticalDelta > horizontalDelta) {
          e.preventDefault();
        }
      }
    }
  },
  mounted() {
    const MusicList = sessionStorage.getItem('musicList');
    if (MusicList) {
      this.musicList = JSON.parse(MusicList);
      this.$store.commit('addMusiclist', this.musicList);
    } else {
      this.musicList = this.$store.state.musicList;
    }
    const el = document.querySelector('.musicList') as HTMLElement;
    el.addEventListener('touchmove', this.handleTouchMove, {
      passive: false
    });

    this.$once('hook:beforeDestroy', () => {
      el.addEventListener('touchmove', this.handleTouchMove, {
        passive: false
      });
    });
  },
});
</script>

<style lang="less">
@import "./index.less";
</style>
